package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class CompanyServlet
 */
@WebServlet(urlPatterns = { "/ProjectType", "/projectType", "/ProjectTypeServlet", "/projectTypeServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class ProjectTypeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public ProjectTypeServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<ProjectTypeModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				getServletContext().getRequestDispatcher("/projectTypeNew.jsp").forward(request, response);
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			ProjectTypeModel query = new ProjectTypeModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<ProjectTypeModel, ProjectTypeModelExt> dal = new GenericDal<ProjectTypeModel, ProjectTypeModelExt>(new ProjectTypeModel());

			ProjectTypeModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("project_type", obj);
				getServletContext().getRequestDispatcher("/projectTypeEdit.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			ProjectTypeModel query = new ProjectTypeModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<ProjectTypeModel, ProjectTypeModelExt> dal = new GenericDal<ProjectTypeModel, ProjectTypeModelExt>(new ProjectTypeModel());

			ProjectTypeModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("project_type", obj);
				getServletContext().getRequestDispatcher("/projectTypeView.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			ProjectTypeModel obj = new ProjectTypeModel();

			// TODO set name here

			GenericDal<ProjectTypeModel, ProjectTypeModelExt> dal = new GenericDal<ProjectTypeModel, ProjectTypeModelExt>(new ProjectTypeModel());

			int res = 0;
			try {
				String txtName = request.getParameter("name");
				obj.setName(txtName);
				res = dal.insert(obj);
				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = createXML("" + res);
					out.println(resultXML);
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {

			ProjectTypeModel obj = new ProjectTypeModel();

			String name = request.getParameter("name");
			obj.setName(name);

			String code = request.getParameter("code");
			obj.setCode(code);

			String description = request.getParameter("description");
			obj.setDescription(description);

			String id_parent = request.getParameter("id_parent");
			if (id_parent != null && !id_parent.isEmpty()) {
				obj.setIdParent(Integer.parseInt(id_parent));
			}

			String is_draft = request.getParameter("is_draft");
			obj.setIsDraft(is_draft.equalsIgnoreCase("true") || is_draft.equalsIgnoreCase("1"));

			obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<ProjectTypeModel, ProjectTypeModelExt> dal = new GenericDal<ProjectTypeModel, ProjectTypeModelExt>(new ProjectTypeModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res > 0) {
					// TODO : success, redirect to somewhere
					// Redirect to some where

				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("project_type", obj);
				getServletContext().getRequestDispatcher("/projectTypeInput.jsp").forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			ProjectTypeModel query = new ProjectTypeModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<ProjectTypeModel, ProjectTypeModelExt> dal = new GenericDal<ProjectTypeModel, ProjectTypeModelExt>(new ProjectTypeModel());

			ProjectTypeModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				String name = request.getParameter("name");
				obj.setName(name);

				String code = request.getParameter("code");
				obj.setCode(code);

				String description = request.getParameter("description");
				obj.setDescription(description);

				String id_parent = request.getParameter("id_parent");
				obj.setIdParent(Integer.parseInt(id_parent));

				String is_draft = request.getParameter("is_draft");
				obj.setIsDraft(is_draft.equalsIgnoreCase("true") || is_draft.equalsIgnoreCase("1"));

				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success
						
						//Redirect to some where
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("project_type", obj);
					getServletContext().getRequestDispatcher("/projectTypeEdit.jsp").forward(request, response);
				}
			} else {
				// TODO data not found
			}
		} else if (mode.equalsIgnoreCase("delete")) {

			ProjectTypeModel query = new ProjectTypeModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<ProjectTypeModel, ProjectTypeModelExt> dal = new GenericDal<ProjectTypeModel, ProjectTypeModelExt>(new ProjectTypeModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
			} else {
				// TODO fail
			}
		}
	}

	protected String createXML(String _id) {
		try {

			DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
			Document doc = docBuilder.newDocument();
			Element project_type = doc.createElement("project_type");
			doc.appendChild(project_type);
			Element e_id = doc.createElement("id");
			project_type.appendChild(e_id);
			Text t_id = doc.createTextNode(_id);
			e_id.appendChild(t_id);

			TransformerFactory transfac = TransformerFactory.newInstance();
			Transformer trans = transfac.newTransformer();
			trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			trans.setOutputProperty(OutputKeys.INDENT, "yes");

			// create string from xml tree
			StringWriter sw = new StringWriter();
			StreamResult result = new StreamResult(sw);
			DOMSource source = new DOMSource(doc);
			trans.transform(source, result);
			String xmlString = sw.toString();

			return xmlString;

		} catch (Exception e) {
			return "error";
		}
	}

}